# --- Setup ---
rm(list = ls())
setwd("/Users/John/Dropbox/")

# --- Load Required Packages ---
library(readr)
library(interflex)
library(tidyverse)
library(ggplot2)
library(cowplot)

# --- Load Dataset ---

df <- as.data.frame(read_csv("JOP_Replication_Materials/data/processed/final_dataset.csv"))

# --- Interflex Model ---
intflex <- df %>%
  dplyr::select(isic, isic2, year, strategic, sqrtta, isic_year, median_share, 
                med_hhi_isic2, med_soe_isic2) %>%
  mutate(Strategic = strategic)

intflex <- as.data.frame(intflex)

# --- Linear Model ---
bin.l <- interflex(estimator = "binning", Y = "sqrtta", D = "Strategic", X = "median_share", 
                   Z = c("med_hhi_isic2", "med_soe_isic2"), 
                   data = intflex, vcov.type = "cluster", cl = c("isic", "year"), 
                   na.rm = TRUE, main = "Marginal Effect of Strategic Status on Tech Absorption\n Linear w/ Cluster Robust SEs", Ylabel = "Tech Absorption Policies", 
                   Xlabel = "Median Processing Share", method = "linear",
                   cex.main = 1, ncols=1, theme.bw = TRUE, nbins = 3, bin.labs = F)

# --- Linear Model ---
bin.nb <- interflex(estimator = "binning", Y = "isic_year", D = "Strategic", X = "median_share", 
                   Z = c("med_hhi_isic2", "med_soe_isic2"), 
                   data = intflex, vcov.type = "cluster", cl = c("isic", "year"), 
                   na.rm = TRUE, main = "Marginal Effect of Strategic Status on Tech Absorption\n NegBin w/ Cluster Robust SEs", Ylabel = "Tech Absorption Policies", 
                   Xlabel = "Median Processing Share", method = "nbinom",
                   cex.main = 1, ncols=1, theme.bw = TRUE, nbins = 3, bin.labs = F)

# --- Extract the figures from the interflex models ---
fig_bin_l <- bin.l$figure  # Linea plot
fig_bin_nb <- bin.nb$figure  # NegBin plot

# ---Combine the plots side-by-side using plot_grid from cowplot ---
combined_figure <- plot_grid(fig_bin_l, fig_bin_nb, labels = NULL, nrow = 1, align = "v")

# --- Save the combined figure to a PDF ---
plot_path <-"JOP_Replication_Materials/appendix/output/C_figure_14.pdf"
ggsave(plot_path, combined_figure, width = 14, height = 6)

browseURL(plot_path)
